<template>
  <div class="hy-form">
    <slot name="header"></slot>
    <el-form :label-width="labelWidth" ref="elFormRef" :model="formData">
      <el-row v-if="formItems && formItems.length">
        <el-col
          :span="8"
          v-bind="colLayout"
          v-for="(item, i) of formItems"
          :key="i"
        >
          <el-form-item
            :rules="item.rules"
            :style="itemLayout"
            :label="item.label"
            :prop="item.key"
          >
            <el-input
              v-if="item.type === 'input'"
              v-bind="item.props"
              v-model="formData[item.key]"
              :placeholder="item.placeholder"
            />
            <el-select
              v-model="formData[item.key]"
              v-else-if="item.type === 'select'"
              v-bind="item.props"
            >
              <template v-if="item.options && item.options.length">
                <el-option
                  v-for="(r, idx) of item.options"
                  :key="idx"
                  :value="r.value"
                  :label="r.label"
                  >{{ r.label }}</el-option
                >
              </template>
            </el-select>

            <el-date-picker
              v-else-if="item.type === 'date'"
              v-model="formData[item.key]"
              type="date"
              v-bind="item.props"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <slot name="footer"></slot>
  </div>
</template>

<script lang="ts">
import { defineComponent, PropType, ref, watch } from 'vue'
import { ElForm } from 'element-plus'
import type { IFormItem } from '../types'
export default defineComponent({
  name: 'HyForm',
  props: {
    modelValue: {
      type: Object,
      required: true
    },
    formItems: {
      type: Array as PropType<IFormItem[]>,
      defaule: () => []
    },
    labelWidth: {
      type: String,
      default: '100px'
    },
    itemLayout: {
      type: Object,
      default: () => ({ padding: `10px` })
    },
    colLayout: {
      type: Object,
      default: () => ({
        xl: 6,
        lg: 8,
        md: 12,
        sm: 24,
        xs: 24
      })
    }
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const formData = ref({ ...props.modelValue })
    const elFormRef = ref<InstanceType<typeof ElForm>>()
    watch(formData, (val) => emit('update:modelValue', val), { deep: true })
    const resetForm = () => {
      elFormRef.value?.resetFields()
    }
    return {
      formData,
      elFormRef,
      resetForm
    }
  }
})
</script>

<style lang="less" scoped>
.hy-form {
  padding-top: 20px;
  padding-right: 10px;
  /deep/ .el-range-editor.el-input__inner {
    width: 100%;
  }
  /deep/ .el-select {
    width: 100%;
  }
  /deep/ .el-date-editor.el-input {
    width: 100%;
  }
}
</style>
